import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state, token) {
    state.token = null
    removeToken(token)
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  setRoutes(state, asyncRoutes) {
    // 将动态路由添加到静态路由里面 方便左侧菜单动态获取路由信息
    state.routes = [...constantRoutes, ...asyncRoutes]
  }
}

const actions = {
  async login(context, data) {
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const data = await getUserInfo()
    context.commit('setUserInfo', data)
    return data
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    // 退出登录清空动态routes 避免同一个浏览器不同角色的用户先后登录 后一个用户没有权限 却能通过修改url的方式访问到前一个用户的权限页面
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
